<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{position: absolute;right: 0;top:200px;width: 200px;height: 40px;line-height: 40px;text-align: center;background: #ccc;}
        #box:active{background: blue;color: #fff;}
    </style>
</head>
<body>
    <span>这是顶部</span>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    123123
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>123
    adasd
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <p>duankuo</p>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <h2>二级标题</h2>
    <div id="box">回到顶部</div>
</body>
<script>
    var obox = document.getElementById("box");
    // 获取obox的初始的top
    var oboxTop = obox.offsetTop;
    // 滚动事件
    onscroll = function(){
        // 滚动时获取滚动的距离
        var t = document.documentElement.scrollTop;
        // 重新设置obox的top为：初始值+新滚动的距离
        obox.style.top = t + oboxTop + "px";
    }

    // =================

    var t2;
    obox.onclick = function(){
        clearInterval(t2);
        // 开启计时器
        t2 = setInterval(function(){
            // 不断的减少滚动的距离
            document.documentElement.scrollTop -= 10;
            // 当滚动的距离等于或小于0时，清除计时器
            if(document.documentElement.scrollTop<=0){
                clearInterval(t2);
            }
        }, 30);
    }


</script>
</html>